package problem123;

//123.买卖股票的最佳时机
//https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int[][] f = new int[n][3];
        int[][] g = new int[n][3];
        //初始化第一行
        f[0][0] = -prices[0];
        for(int j = 1; j<3; j++) {
            f[0][j] = -0x3f3f3f;
            g[0][j] = -0x3f3f3f;
        }
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= 2; j++) {
                f[i][j] = Math.max(f[i - 1][j], g[i - 1][j] - prices[i]);
                g[i][j] = g[i - 1][j];
                if(j-1>=0) g[i][j] = Math.max(g[i][j], f[i-1][j-1] + prices[i]);
            }
        }

        int ret = 0;
        for(int j = 0; j<=2; j++) {
            ret = Math.max(ret, g[n-1][j]);
        }
        return ret;
    }
}

/*

f[i][j]:第i天结束后, 完成了j次交易, 处于 买入 状态, 此时的最大利润
g[i][j]:第i天结束后, 完成了j次交易, 处于 卖出 状态, 此时的最大利润
f[i][j] = Math.max(f[i - 1][j], g[i - 1][j - 1] - prices[i]);
g[i][j] = Math.max(g[i - 1][j], f[i - 1][j-1] + prices[i]);

 */